﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TVersityDotNet.HelperTypes
{
    /// <summary>
    /// Type to translate connection settings to/from TVersity.  
    /// TVersity stores speed and quality in the same setting; TVersityDotNet splits them into two logical settings items
    /// </summary>
    public class ConnectionSettingsContainer
    {
        /// <summary>
        /// Ctor, with string-based initializer
        /// </summary>
        /// <param name="settingsText">Settings text containing the TVersity settings</param>
        public ConnectionSettingsContainer(string settingsText)
        {
            Parse(settingsText);
        }

        /// <summary>
        /// Ctor, with member initializers
        /// </summary>
        /// <param name="quality">Initial quality value</param>
        /// <param name="speed">Initial speed value</param>
        public ConnectionSettingsContainer(ConnectionQualityOption quality, ConnectionSpeedOption speed)
        {
            this.Quality = quality;
            this.Speed = speed;
        }

        /// <summary>
        /// Connection quality
        /// </summary>
        public ConnectionQualityOption Quality { get; set; }

        /// <summary>
        /// Connection speed
        /// </summary>
        public ConnectionSpeedOption Speed { get; set; }

        private void Parse(string settingsText)
        {
            string qualityText;
            string speedText;

            var settingsItems = settingsText.Split(new string[] {"_"}, StringSplitOptions.None);
            if (settingsItems.Length > 2)
            {
                qualityText = settingsItems[settingsItems.Length - 1];
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < settingsItems.Length - 1; i++)
                {
                    if (i > 0)
                    {
                        sb.Append("_");
                    }
                    sb.Append(settingsItems[i]);
                }
                speedText = sb.ToString();
            }
            else
            {
                qualityText = settingsItems[1];
                speedText = settingsItems[0];
            }

            this.Quality = (ConnectionQualityOption)Enum.Parse(typeof(ConnectionQualityOption), qualityText, true);
            this.Speed = (ConnectionSpeedOption)Enum.Parse(typeof(ConnectionSpeedOption), speedText, true);
        }

        /// <summary>
        /// Override the ToString() member to output a TVersity-friendly settings option
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return string.Concat(this.Speed.ToString(), "_", this.Quality.ToString());
        }
    }
}
